import time
import asyncio
import datetime

from typing import Tuple,List,Any
from loguru import logger
from app.database.db_sqlite import async_db_session
from app.schemas.job import ReqCreateJob
from app.schemas.sche import ReqJob
from app.schemas.task import RQRunTask
from app.sche_task import schedulerIns
from apscheduler.triggers.cron import CronTrigger
from app.utils.generate_string import get_uuid 
from app.crud import crud_job
from app.api.service import task_service

# ============================================== 巡检进行定时巡检的函数================================================
def run_const_temp_humi():
    """执行定时巡检的函数
    """
    try:
        task_service.run_task(RQRunTask(task_name='task_1691995180'))
    except Exception as e:
        logger.error('定时任务执行失败');

# =================================================service =================================================================================================

async def add_scheduler(params:ReqCreateJob):
    async with async_db_session() as db:
        new_params = params.dict()
        new_params.update({
            "job_id":get_uuid()
        })
        await crud_job.create_job(db,new_params)

        # logger.debug(new_params);
        # logger.debug(params.cron);
        # schedulerIns.add_job(id=new_params["job_id"], func=run_const_temp_humi, trigger=CronTrigger.from_crontab("45 12 * * *"))

        if params.func =="run_const_temp_humi":
            schedulerIns.add_job(id=new_params["job_id"], func=run_const_temp_humi, trigger=CronTrigger.from_crontab(params.cron))
        else:
            pass





async def get_schedulers():
    async with async_db_session() as db:
        jobs = schedulerIns.get_jobs()
        jobs_dict = []
        for job in jobs:
            if job.id=='all1_info' or job.id=='temp_humi':
                continue
            job_dict = {
                "id": job.id,
                "next_run_time": str(job.next_run_time),
            }
            # 补全定时任务的其他信息
            res = await crud_job.get_job_by_job_id(db,job.id)
            if res is None:
                return []
            job_dict.update(res.__dict__)
            jobs_dict.append(job_dict)
        return jobs_dict




async def get_scheduler_by_id(job_id:str):
    async with async_db_session() as db:
        job = schedulerIns.get_job(job_id)
        job_dict = {
            "id": job.id,
            "next_run_time": str(job.next_run_time),
        }
        # 补全定时任务的其他信息
        res = await crud_job.get_job_by_job_id(db,job.id)
        job_dict.update(res.__dict__)
        return job_dict



async def del_scheduler(job_id:str):
    async with async_db_session() as db:
        await crud_job.del_job_by_job_id(db,job_id)
        schedulerIns.remove_job(job_id)
